package com.ca.ridersclubapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.CaptchaRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.LoginRequester;
import com.ca.ridersclubapplication.request.dto.LoginResult;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.ImmersiveActivity;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ea.ui.core.basic.EAButton;
import com.ea.ui.core.basic.EAInput;
import com.ea.ui.core.basic.EALink;
import com.ea.ui.core.util.Type;

import java.util.Objects;

public class OtherLoginActivity extends ImmersiveActivity {

    //  头像相关
    private ImageView headerImageView;

    //  连接相关
    private EALink emailErrorLink;
    private EALink codeErrorLink;

    //  输入框相关
    private EAInput emailInput;
    private EAInput codeInput;

    //  按钮相关
    private EAButton codeButton;
    private EAButton loginButton;
    private EAButton backButton;
    private int btnType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_login);

        //  判断是否已经登录
        SharedPreferences login = getSharedPreferences("login", MODE_PRIVATE);
        if (login != null) {
            String email = login.getString("email", "");
            long id = login.getLong("id", 0);
            String token = login.getString("token", "");
            if (!email.isEmpty() || id != 0 || !token.isEmpty()) {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }

        //  初始化并设置视图
        init();

        //  设置动画
        setViewTransition();
    }

    /**
     * 初始化：视图、Retrofit服务接口，并对视图进行设置
     */
    private void init() {

        //  头像相关
        headerImageView = findViewById(R.id.iv_header);
        headerImageView.setAlpha(0f);

        //  连接相关
        emailErrorLink = findViewById(R.id.link_error_email);
        codeErrorLink = findViewById(R.id.link_error_code);

        //  输入框相关
        emailInput = findViewById(R.id.ipt_email);
        codeInput = findViewById(R.id.ipt_code);

        //  按钮相关
        codeButton = findViewById(R.id.btn_code);
        loginButton = findViewById(R.id.btn_login);
        backButton = findViewById(R.id.btn_back);

        //  设置按钮
        setCodeButton();
        setLoginButton();
        setBackButton();

        //  设置输入框
        setEmailInput();
        setCodeInput();
    }


    /**
     * 设置动画
     */
    private void setViewTransition() {

        backButton.setTransitionName("link:other");
        emailInput.setTransitionName("input:email");
        codeInput.setTransitionName("input:password");
        loginButton.setTransitionName("button:login");
    }


    /**
     * 设置返回按钮
     * 实现：
     *      1、点击按钮返回登录页面
     */
    private void setBackButton() {
        backButton.setOnClickListener(view -> {
            finishAfterTransition();
        });
    }


    /**
     * 设置 email 输入框
     * 实现：
     *      1、输入邮箱自动请求并显示头像
     *      2、email输入框 和 password输入框 同时通过校验时，开启登录按钮点击
     */
    private void setEmailInput() {

        emailInput.requestFocus();

        emailInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    //  email输入框 和 password输入框 内容检查，设置按钮是否可用
                    checkAllInput();

                    //  设置 code 按钮是否可用
                    boolean flag = emailInput.isVerify() && emailErrorLink.getText().toString().isEmpty();
                    codeButton.setDisable(!flag);

                    if (emailInput.isVerify()) {

                        String email = Objects.requireNonNull(emailInput.getText()).toString();

                        //  查询账号是否存在
                        AccountRequester.getIdByEmail(OtherLoginActivity.this, email, new AfterExecutor<Long>() {
                            @Override
                            public void execute(Result<Long> result) {
                                if (result.isSuccess()) {
                                    //  如果账号存在，则加载头像
                                    emailErrorLink.setText("");
                                    ImageUtils.loadCircleImage(OtherLoginActivity.this, FileRequester.HEADER_BY_EMAIL_BASE_URL + email, headerImageView);
                                    headerImageView.setAlpha(1f);
                                }
                                else {
                                    emailInput.setType(Type.DANGER);
                                    emailErrorLink.setText(result.getMessage());
                                    headerImageView.setAlpha(0f);
                                }

                                checkAllInput();
                                //  设置 code 按钮是否可用
                                boolean flag = emailInput.isVerify() && emailErrorLink.getText().toString().isEmpty();
                                codeButton.setDisable(!flag);
                            }
                        });
                    }
                    else {
                        emailErrorLink.setText("请输入正确的邮箱");
                    }

                    checkAllInput();
                    //  设置 code 按钮是否可用
                    flag = emailInput.isVerify() && emailErrorLink.getText().toString().isEmpty();
                    codeButton.setDisable(!flag);
                }
                else {
                    emailErrorLink.setText("");
                }
            }
        });

        //  判断是否有 email 传入
        String email = getIntent().getStringExtra("email");
        if (email != null && !email.isEmpty()) {
            emailInput.setText(email);
        }
    }


    /**
     * 设置 code 输入框
     * 实现：
     *      1、输入内容时，显示校验失败提示
     *      2、email输入框、nickname输入框、password输入框 和 code输入框 同时通过校验时，开启注册按钮点击
     */
    private void setCodeInput() {

        codeInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {

                    //  输入框 内容检查，设置按钮是否可用
                    checkAllInput();

                    if (!codeInput.verify()) {
                        codeErrorLink.setText(R.string.tip_input_code);
                    }
                    else {
                        codeErrorLink.setText("");
                    }

                    checkAllInput();
                }
                else {
                    codeErrorLink.setText("");
                }
            }
        });
    }


    /**
     * 验证输入框内容
     */
    private void checkAllInput() {

        boolean flag = emailInput.isVerify() && codeInput.isVerify()
                && emailErrorLink.getText().toString().isEmpty()
                && codeErrorLink.getText().toString().isEmpty();

        if (flag) {
            loginButton.setType(Type.PRIMARY);
            loginButton.setDisable(false);
        }
        else {
            loginButton.setType(btnType);
            loginButton.setDisable(true);
        }
    }


    /**
     * 设置 code 按钮
     * 实现：
     *      1、点击发送获取验证码请求
     */
    private void setCodeButton() {
        codeButton.setOnClickListener(view -> {

            codeButton.setDisable(true);

            String email = Objects.requireNonNull(emailInput.getText()).toString();
            CaptchaRequester.sendCaptcha(this, email, "账号登录", new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {

                        //  发送验证码成功
                        Toast.makeText(OtherLoginActivity.this, "发送成功", Toast.LENGTH_SHORT).show();

                        //  开启 60s 倒计时
                        new CountDownTimer(60 * 1000, 1000) {

                            private final String codeBtnText = codeButton.getText().toString();
                            private int m = 60;

                            @Override
                            public void onTick(long millisUntilFinished) {
                                codeButton.setDisable(true);
                                String text = (m > 9 ? (m + "") : ("0" + m)) + "s后再试";
                                codeButton.setText(text);
                                m--;
                            }

                            @Override
                            public void onFinish() {
                                codeButton.setText(codeBtnText);
                                codeButton.setDisable(false);
                            }
                        }.start();
                    }
                    else {
                        Toast.makeText(OtherLoginActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        codeButton.setDisable(false);
                    }
                }
            });
        });
    }


    /**
     * 设置 登录 按钮
     * 实现：
     *      1、点击登录按钮发起登录请求
     */
    private void setLoginButton() {

        //  缓存按钮原 type
        btnType = loginButton.getType();

        loginButton.setOnClickListener(v -> {

            //  将按钮置为不可用，防止多次点击
            loginButton.setDisable(true);

            if (!codeInput.verify()) {
                codeErrorLink.setText(R.string.tip_input_code);
            }

            if (emailInput.verify() && codeInput.verify()) {

                //  输入内容校验通过，发起登录请求
                String email = Objects.requireNonNull(emailInput.getText()).toString();
                String code = Objects.requireNonNull(codeInput.getText()).toString();
                LoginRequester.loginByCaptcha(OtherLoginActivity.this, null, email, code, new AfterExecutor<LoginResult>() {
                    @Override
                    public void execute(Result<LoginResult> result) {
                        if (result.isSuccess()) {
                            //  登录成功后关闭当前Activity
                            finishAfterTransition();
                        }
                        else {
                            Toast.makeText(OtherLoginActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }
}